<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 0;
$keyword = isset($_GET['keyword']) ? $conn->real_escape_string($_GET['keyword']) : '';

$sql = "SELECT c.*, cc.name as category_name 
        FROM coaches c 
        LEFT JOIN coach_categories cc ON c.category_id = cc.id 
        WHERE c.status = 1";

if ($category_id > 0) {
    $sql .= " AND c.category_id = $category_id";
}

if (!empty($keyword)) {
    $sql .= " AND c.name LIKE '%$keyword%'";
}

$sql .= " ORDER BY c.rating DESC";

$result = $conn->query($sql);

$coaches = [];
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $coaches[] = $row;
    }
}

echo json_encode([
    'status' => 'success',
    'coaches' => $coaches
]);

$conn->close();
?> 